#include "aip8563_app.h"

#if _REAL_TIME_CLOCK_SOURCE_ == _EXTERNAL_CLOCK_SOURCE_

void Aip8563SetDefaultParmaeter(void)
{
  Aip8563WriteRegister(AIP8563_CONTORL_BIT_1, 0x00);
  Aip8563WriteRegister(AIP8563_CONTORL_BIT_2, 0x11);
  Aip8563WriteRegister(AIP8563_MINUTE_ALARM, 0x80);
  Aip8563WriteRegister(AIP8563_HOUR_ALARM, 0x80);
  Aip8563WriteRegister(AIP8563_DATE_ALARM, 0x80);
  Aip8563WriteRegister(AIP8563_WEEK_ALARM, 0x80);
  Aip8563WriteRegister(AIP8563_CLK_OUT_SET, 0x80);
}

void Aip8563GetRealTimeTime(TimeFormat_t *pRealTimeTime)
{
  TimeFormat_t GetRealTimeTime = {0};

  if (pRealTimeTime != NULL)
  {
    GetRealTimeTime.Year = Aip8563ReadRegister(AIP8563_REAL_TIME_YEAR);
    GetRealTimeTime.Month = Aip8563ReadRegister(AIP8563_REAL_TIME_MONTH) & 0x1F;
    GetRealTimeTime.Week = Aip8563ReadRegister(AIP8563_REAL_TIME_WEEK) & 0x07;
    GetRealTimeTime.Date = Aip8563ReadRegister(AIP8563_REAL_TIME_DAY) & 0x3F;
    GetRealTimeTime.Hour = Aip8563ReadRegister(AIP8563_REAL_TIME_HOUR) & 0x3F;
    GetRealTimeTime.Minute = Aip8563ReadRegister(AIP8563_REAL_TIME_MINUTE) & 0x7F;
    GetRealTimeTime.Second = Aip8563ReadRegister(AIP8563_REAL_TIME_SECOND) & 0x7F;

    pRealTimeTime->Date = BcdToHex(GetRealTimeTime.Date);
    pRealTimeTime->Year = BcdToHex(GetRealTimeTime.Year) + 2000;
    pRealTimeTime->Hour = BcdToHex(GetRealTimeTime.Hour);
    pRealTimeTime->Week = BcdToHex(GetRealTimeTime.Week);
    pRealTimeTime->Month = BcdToHex(GetRealTimeTime.Month);
    pRealTimeTime->Minute = BcdToHex(GetRealTimeTime.Minute);
    pRealTimeTime->Second = BcdToHex(GetRealTimeTime.Second);
  }
}

void Aip8563SetRealTimeTime(TimeFormat_t *pRealTimeTime)
{
  TimeFormat_t SetRealTimeTime = {0};

  if (pRealTimeTime != NULL)
  {
    SetRealTimeTime.Date = HexToBcd(pRealTimeTime->Date);
    SetRealTimeTime.Year = HexToBcd(pRealTimeTime->Year - 2000);
    SetRealTimeTime.Week = HexToBcd(pRealTimeTime->Week);
    SetRealTimeTime.Hour = HexToBcd(pRealTimeTime->Hour);
    SetRealTimeTime.Month = HexToBcd(pRealTimeTime->Month);
    SetRealTimeTime.Minute = HexToBcd(pRealTimeTime->Minute);
    SetRealTimeTime.Second = HexToBcd(pRealTimeTime->Second);

    Aip8563WriteRegister(AIP8563_REAL_TIME_SECOND, SetRealTimeTime.Second);
    Aip8563WriteRegister(AIP8563_REAL_TIME_MINUTE, SetRealTimeTime.Minute);
    Aip8563WriteRegister(AIP8563_REAL_TIME_HOUR, SetRealTimeTime.Hour);
    Aip8563WriteRegister(AIP8563_REAL_TIME_DAY, SetRealTimeTime.Date);
    Aip8563WriteRegister(AIP8563_REAL_TIME_WEEK, SetRealTimeTime.Week);
    Aip8563WriteRegister(AIP8563_REAL_TIME_MONTH, SetRealTimeTime.Month);
    Aip8563WriteRegister(AIP8563_REAL_TIME_YEAR, SetRealTimeTime.Year);
  }
}

void Aip8563Configuration(void)
{
  Aip8563SetDefaultParmaeter();
  Aip8563BoardInitialisation();
}

#endif